import { Component, NgZone, ViewChild, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { RestService } from '../../services/rest.service';
import { ActionTypes, SexEnums } from '../../models/wdl-types';

import * as _ from 'lodash';

@Component({
  selector: 'app-nurse-dialog',
  templateUrl: './nurse-dialog.component.html',
  styleUrls: ['./nurse-dialog.component.css']
})
export class NurseDialogComponent implements OnInit {
  formGroup: FormGroup;
  item: any;
  institution: any;
  title = '';
  error = '';

  // could be add, modify, read
  mode = ActionTypes.ADD;
  disabled = false;
  departments = [];

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<NurseDialogComponent>,
              fb: FormBuilder,
              private ngZone: NgZone,
              private translate: TranslateService,
              private rest: RestService,
              private dialog: MatDialog) {
    this.institution = dialogData.institution;
    this.mode = dialogData.mode;

    if (this.mode === ActionTypes.ADD) {
      this.title = this.translate.get("add")['value'] + this.translate.get("nurse")['value'];
    } else if (this.mode === ActionTypes.MODIFY) {
      this.item = dialogData.item;
      this.title = this.translate.get("edit")['value'];
    }

    const formSettings = {
      nurseName: [
        { value: '', disabled: this.mode === ActionTypes.MODIFY},
        [
          Validators.required,
          Validators.maxLength(64)
        ]
      ],
      sex: [
        'female',
        [
          Validators.required,
        ]
      ],
      departmentName: [ '', [] ],
      tel: [
        '',
        [
          Validators.required,
          Validators.maxLength(12)
        ]
      ]
    };

    this.formGroup = fb.group(formSettings);

    if (this.mode === ActionTypes.MODIFY) {
      _.forEach(this.formGroup.controls, (value, key) => {
        if (key === 'sex') {
          value.value = this.item[key] === 'MALE' ? 'male' : 'female';
        } else {
          value.value = this.item[key];
        }
      });
    }
  }

  disableSubmit() {
    return this.formGroup.invalid || (this.mode === ActionTypes.MODIFY && !this.formGroup.dirty);
  }

  submit() {
    const data = {};
    _.forEach(this.formGroup.value, (value, key) => {
      if (key === 'sex') {
        data[key] = value === 'male' ? SexEnums.MALE : SexEnums.FEMAIL;
      } else {
        data[key] = _.trim(value);
      }
    });

    if (this.mode === ActionTypes.ADD) {
      this.rest.getWithParams('data/nurse/search/nurseName', {
        institutionId: this.institution.id,
        nurseName: data['nurseName']
      }).subscribe(resp => {
        if (resp['_embedded']['nurses'].length > 0) {
          this.error = 'nurseNameExists';
        } else {
          this.dialogRef.close(data);
        }
      }, message => {
        this.error = 'validateNurseNameError';
      });
    } else {
      this.dialogRef.close(data);
    }
  }

  ngOnInit() {
    this.rest.get('data/institution/' + this.institution.id + '/departments').subscribe(data => {
      this.departments = data['_embedded']['departments'];
    }, () => {
      console.error('Failed to get departments for institution: ' + this.institution.instName);
    })
  }
}